clear all
global system "linux"

if "${system}" == "linux" {
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"
cd "${code}/tba_elig"


use "${temp}/lps-prep.dta", clear

keep if year <= 2012

rename fico credit_score
rename debt_to_income_ratio debt_to_income

// adjust lps variables
gen tbaelig = orig_loan_amount <= 417000
gen origcombltv = orig_loan_to_value
gen diff_debt_to_income = 0

gen rate = orig_rate/1200
gen monthly = orig_loan_amount* rate* (1 + rate)^360 / ((1 + rate)^360 -1)
gen income =  monthly/debt_to_income
gen mtoi = orig_loan_amount / income

gen Orig=1

// specifications
do "_embs-lps-spec.do"
rename notba hibal


*** 2. reg- plots
gen PaboveC1 = PaboveC
gen PaboveC2 = PaboveC * PaboveC 
gen PaboveC3= PaboveC2* PaboveC
 

gen bin = ceil(PaboveC/2.5)*2.5

global poly1 "PaboveC 1.HiP#c.PaboveC1"
global poly2 "$poly1 PaboveC2 1.HiP#c.PaboveC2"
global poly3 "$poly2 PaboveC3 1.HiP#c.PaboveC3"

foreach x of varlist hibal orig_rate {

	local bw = 150

	reghdfe `x' $poly3 $controls i.agency_id if abs(PaboveC)<=`bw', a(FE1=i.prop_zip_code FE2=i.orig_ym FE4=i.LLPAbin)  vce(robust)

	predict resid, r 
	
	foreach z in $poly3 {
		replace resid = resid + _b[`z']* (`z')
	}
	
	preserve
		keep if abs(PaboveC)<=`bw'
		qui su `x' if HiP == 0
		replace resid = resid + `r(mean)'
		collapse resid, by(bin) fast
		twoway scatter resid bin, xline(0) xlabel(-150(50)150) ytitle("") ylabel(, angle(0)) 
		graph export "${figure}/rdplot-lps-only-`x'.pdf", replace
	restore
	drop resid 
	drop FE*
}
